import { useRoute, useRouter } from 'vue-router'
import { reactive, toRefs, watch } from 'vue'
import { useI18n } from 'vue-i18n'

type Breadcrumb = {
  title: string
  route?: string
  parentPath?: string
}

export default () => {
  const router = useRouter()
  const route = useRoute()
  const { t } = useI18n()
  const state = reactive({
    breadcrumbs: [] as Breadcrumb[]
  })
  watch(
    route,
    () => {
      const parentPath = (route.query.parentPath as string) || ''
      const breadcrumbs = parentPath
        .split('@@@')
        .filter((path) => path)
        .reduce((breadcrumbs, title, i) => {
          const parentPath = (breadcrumbs[i - 1]?.parentPath || '') + title + '@@@'
          breadcrumbs.push({ title, parentPath })
          return breadcrumbs
        }, [] as Breadcrumb[])
      breadcrumbs.unshift({
        title: t(route.meta.title + ''),
        route: route.path
      })
      state.breadcrumbs = breadcrumbs
    },
    { immediate: true }
  )

  const jumbRouter = (breadcrumb: Breadcrumb) => {
    if (breadcrumb.route) router.replace({ path: breadcrumb.route })
    if (breadcrumb.parentPath) router.replace({ query: { parentPath: breadcrumb.parentPath } })
  }

  return {
    ...toRefs(state),
    /** 跳转路由 */
    jumbRouter
  }
}
